package com.gulimall.ware.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gulimall.common.constrant.WareConstant;
import com.gulimall.common.utils.PageUtils;
import com.gulimall.common.utils.Query;
import com.gulimall.ware.dao.PurchaseDao;
import com.gulimall.ware.entity.PurchaseDetailEntity;
import com.gulimall.ware.entity.PurchaseEntity;
import com.gulimall.ware.service.PurchaseDetailService;
import com.gulimall.ware.service.PurchaseService;
import com.gulimall.ware.service.WareSkuService;
import com.gulimall.ware.vo.PurchaseDoneVo;
import com.gulimall.ware.vo.PurchaseMergeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {
    @Autowired
    private PurchaseDetailService purchaseDetailService;
    @Autowired
    private WareSkuService wareSkuService;
    private boolean flag;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>());

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryUnReceiveList(Map<String, Object> params) {
        return new PageUtils(this.page(new Query<PurchaseEntity>().getPage(params), new QueryWrapper<>()));
    }

    @Override
    @Transactional
    public void saveMergePurchase(PurchaseMergeVo mergeVo) {
        Long purchaseId = mergeVo.getPurchaseId();
        if (purchaseId == null) {
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setUpdateTime(new Date());
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.ASSIGNED.getCode());
            purchaseEntity.setPriority(0);

            save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }

        Long finalPurchaseId = purchaseId;

        List<PurchaseDetailEntity> detailEntities = mergeVo.getItems().stream().map(item -> {
            PurchaseDetailEntity detailEntity = purchaseDetailService.getById(item);
            detailEntity.setPurchaseId(finalPurchaseId);
            detailEntity.setId(item);
            detailEntity.setStatus(detailEntity.getStatus() > 1 ? -1 :
                    WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
            return detailEntity;
        }).filter(entity -> entity.getStatus() != -1).collect(Collectors.toList());

        purchaseDetailService.updateBatchById(detailEntities);
    }

    @Override
    public void savePurchase(PurchaseEntity purchase) {
        purchase.setUpdateTime(new Date());
        purchase.setCreateTime(new Date());
        purchase.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());

        save(purchase);
    }

    @Override
    public void updatePurchase(PurchaseEntity purchase) {
        purchase.setUpdateTime(new Date());

        updateById(purchase);
    }

    @Override
    public void receivedPurchase(List<Long> purchaseItem) {
        //确定当前采购单状态
        List<PurchaseEntity> purchaseEntities = purchaseItem.stream().map(this::getById).filter(item -> {
            return item.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode() || item.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode();
        }).peek(item -> {
            item.setUpdateTime(new Date());
            item.setStatus(WareConstant.PurchaseStatusEnum.PURCHASING.getCode());
        }).collect(Collectors.toList());

        //改变采购单状态
        updateBatchById(purchaseEntities);

        //改变采购项状态
        purchaseEntities.forEach(item -> {
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
            detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.RECEIVED.getCode());
            detailEntity.setPurchaseId(item.getId());
            purchaseDetailService.update(detailEntity, new QueryWrapper<PurchaseDetailEntity>().eq("purchase_id",
                    item.getId()));
        });
    }

    @Override
    @Transactional
    public void donePurchase(PurchaseDoneVo purchaseDoneVo) {
        //改变采购项状态
        flag = true;
        List<PurchaseDetailEntity> detailEntities = purchaseDoneVo.getItems().stream().map(item -> {
            PurchaseDetailEntity purchaseDetail = purchaseDetailService.getById(item.getItemId());
            if (item.getStatus() == WareConstant.PurchaseDetailStatusEnum.EXCEPTION.getCode()) {
                flag = false;
                purchaseDetail.setStatus(purchaseDetail.getStatus());
            } else {
                purchaseDetail.setStatus(WareConstant.PurchaseDetailStatusEnum.COMPLETED.getCode());
            }

            //将成功采购的商品入库
            wareSkuService.saveProductWare(purchaseDetail.getSkuId(), purchaseDetail.getWareId(),
                    purchaseDetail.getSkuNum());

            return purchaseDetail;
        }).collect(Collectors.toList());

        purchaseDetailService.updateBatchById(detailEntities);

        //改变采购状态
        Long purchaseId = purchaseDoneVo.getId();
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseId);
        purchaseEntity.setStatus(flag ? WareConstant.PurchaseStatusEnum.COMPLETED.getCode() :
                WareConstant.PurchaseStatusEnum.FAILED.getCode());
        purchaseEntity.setUpdateTime(new Date());
        updateById(purchaseEntity);
    }

}
